// Editor
import React from 'react';

import { Checkbox, Radio } from 'zent';
import { Row, Col, Tabs, Select, Input, InputNumber, Table, Button, TreeSelect, Spin } from 'antd';
import { DesignEditor, ControlGroup, } from 'zent/lib/design/editor/DesignEditor';
import { connect } from 'dva';
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
export const PLACEHOLDER = '请填写内容，如果过长，将会在手机上滚动显示';
import styles from './index.less';
import { CurryRight } from 'lodash-decorators';
import ProductModal from './ProductModal';
import { DragDropContext, DragSource, DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import {
  STYLE,
  PRODUCT_LAYOUT,
  PRODUCT_LIMIT,
  PRODUCT_ENTRY_UUID_KEY,
  PRODUCT_DND_TYPE
} from './constants';
import { exec } from 'child_process';
let dragingIndex = -1;
class BodyRow extends React.Component {
    componentWillMount() {
        window.Isoption = false;
      }
      componentDidMount() {
        window.Isoption = true;
      }
  render() {

    const {
      isOver,
      connectDragSource,
      connectDropTarget,
      moveRow,
      ...restProps
    } = this.props;
    const style = { ...restProps.style, cursor: 'move' };

    let className = restProps.className;
    if (isOver) {
      if (restProps.index > dragingIndex) {
        className += ' drop-over-downward';
      }
      if (restProps.index < dragingIndex) {
        className += ' drop-over-upward';
      }
    }

    return connectDragSource(
      connectDropTarget(
        <tr
          {...restProps}
          className={className}
          style={style}
        />
      )
    );
  }
}
const rowSource = {
  beginDrag(props) {

    dragingIndex = props.index;
    return {
      index: props.index,
    };
  },
};

const rowTarget = {
  drop(props, monitor) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Time to actually perform the action
    props.moveRow(dragIndex, hoverIndex);

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  },
};

const DragableBodyRow = DropTarget(
  'row',
  rowTarget,
  (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
  }),
)(
  DragSource(
    'row',
    rowSource,
    (connect) => ({
      connectDragSource: connect.dragSource(),
    }),
  )(BodyRow),
);
@connect(({ global, goods, pruductSellList, loading }) => ({
  oemInfo: global.oemInfo,
  pruductSellList: pruductSellList.pruductSellList,
  loading: loading.effects['pruductSellList/GetSellProductList'],
  goods,
}))

class ProductEditor extends DesignEditor {
  componentDidMount() {
    const { value: { cid, topNum } } = this.props;
    console.log(this.props.value)
    let arr = []
    cid.map(item => {
      let id = item.split('0-0-')[1] || 0;
      if (id != 0) {
        arr.push(id);
      }
    });

    this.setState({ selectValue: arr, selectTopnum: topNum }, () => {
      this.GetFirstAndSecondList();
      this.GetProductList();
    })

  }
  components = {
    body: {
      row: DragableBodyRow,
    },
  }
  state = {
    treeData: [],
    selectValue: [],
    //临时记录排序，在生命周期中对比，如果一样 就不请求接口，节约开销
    selectSort: 1,
    //临时记录商品数量，在生命周期中对比，如果一样 就不请求接口，节约开销
    selectTopnum: 2,
    //临时记录数据来源，在生命周期中对比，如果一样 就不请求接口，节约开销
    selectTap: 1,
  }

  render() {
    const { prefix, showError, validation, value, loading } = this.props;
    const { treeData } = this.state

    const columns = [{
      title: 'ImgUrl',
      dataIndex: 'ImgUrl',
      key: 'ImgUrl',
      width: '11.5%',
      render: (text, item) => (
        <img src={`${window.cdnUrl}/${item.ImgUrl}`} />
      ),
    }, {
      title: 'Name',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '操作',
      dataIndex: 'act',
      key: 'act',
      width: '12%',
      align: 'right',
      render: (text, item) => (
        <a onClick={() => this.deleteProduct(item.Id)}>删除</a>
      ),
    }];
    return (
      <div className={styles.Product}>
        <div className={`xkd-moduleTitle`} style={{ fontSize: '14px' }}>商品模块</div>
        <Row>
          <Col span={3} className="xkd-font14 xkd-text-right">列表样式：</Col>
          <Col span={21}>
            <ControlGroup>
              <RadioGroup onChange={this.SetProductLayout} value={value.productLayout}>
                <Radio value={1}>一行两个</Radio>
                <Radio value={2}>一行三个</Radio>
                <Radio value={3}>垂直列表</Radio>
                <Radio value={4}>一行一个</Radio>
              </RadioGroup>
            </ControlGroup>
          </Col>
        </Row>
        <Row>
          <Col span={3} className="xkd-font14 xkd-text-right">显示内容：</Col>
          <Col span={21}>
            <ControlGroup className='ShowOpts'>
              <CheckboxGroup value={value.showOpts} onChange={this.SetShowOpts}>
                <Checkbox value={1}>商品名称</Checkbox><br />
                <Checkbox value={2}>商品卖点</Checkbox><br />
                <Checkbox value={3}>商品价格</Checkbox><br />
                <Checkbox value={4}>购买按钮</Checkbox>
              </CheckboxGroup>
            </ControlGroup>
            {
              value.showOpts.filter(item => item === 4).length > 0 ? <ControlGroup className='RightRadio' >
                <RadioGroup value={value.style} onChange={this.SetProductStyle}>
                  <Radio value={1}>样式一</Radio>
                  <Radio value={2}>样式二</Radio>
                  <Radio value={3}>样式三</Radio>
                  <Radio value={4}>样式四</Radio>
                </RadioGroup>
              </ControlGroup> : null
            }

          </Col>
        </Row>
        <Tabs type="card" onChange={this.SetDataFrom} activeKey={`${value.dataFrom}`}>
          <TabPane tab="自动选择商品" key={1}>
            <Spin spinning={loading} >
              <Row>
                <Col span={3}>商品分类：</Col>
                <Col span={21}>
                  <TreeSelect
                    treeData={treeData}
                    value={value.cid}
                    onChange={this.SetCid}
                    treeCheckable={true}
                    showCheckedStrategy={TreeSelect.SHOW_CHILD}
                    searchPlaceholder={'请选择'}
                    allowClear={true}
                    showSearch={false}
                    style={{ width: 256 }}
                  />

                </Col>
              </Row>
              <Row>
                <Col span={3}>商品排序：</Col>
                <Col span={21}>
                  <Select placeholder="请选择" style={{ width: 256 }} onChange={this.SetSort} value={value.sort}>
                    <Option value={1}>最新上架</Option>
                    <Option value={2}>销量从高到低</Option>
                    <Option value={3}>价格从高到低</Option>
                    <Option value={4}>价格从低到高</Option>
                  </Select>
                </Col>
              </Row>
              <Row>
                <Col span={3}>商品数量：</Col>
                <Col span={21}>
                  <InputNumber max={50} min={1} value={value.topNum} onChange={this.SetTopNum} style={{ width: 256 }} placeholder="最多支持50个" />
                </Col>
              </Row>
            </Spin>
          </TabPane>

          <TabPane tab="手动选择商品" key={2}>
            <Row>
              <Col span={5}>
                <Button onClick={() => {
                  const title = `已上架商品`;

                  this.ProductModal.show({ title, selectId: value.selectId }, this.SetGoodList)

                }}>选择商品</Button>
              </Col>
              <Col span={5} offset={14} className='text-right'>上下拖动可排序</Col>
            </Row>
            <Table
              columns={columns}
              dataSource={value.list ? value.list : []}
              pagination={false}
              showHeader={false}
              components={this.components}
              onRow={(record, index) => ({
                index,
                moveRow: this.moveRow,
              })}

            />
          </TabPane>
        </Tabs>
        <ProductModal
          ref={e => {
            this.ProductModal = e;
          }}
        />
      </div>
    );
  }

  static designType = 'product';
  static designDescription = '商品';
  static getInitialValue(settings, globalConfig) {
    return {
      style: STYLE.TWO,
      productLayout: PRODUCT_LAYOUT.VERTICAL,
      showOpts: [1, 2, 3, 4],
      list: [],
      cid: [],
      topNum: 2,
      sort: 1,
      dataFrom: 1,
      selectId: [],
    };
  }

  moveRow = (dragIndex, hoverIndex) => {
    const { list } = this.props.value;
    const dragRow = list[dragIndex];

    this.props.onChange(update(this.props.value, {
      list: {
        $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
      },
    })
    );


  }
  SetGoodList = (data) => {
    const { value: { list, selectId } } = this.props;
    let listMap = list
    let selectIdMap = selectId
    data.forEach(item => {
      if (listMap.length < 50) {
        if (!listMap.filter(i => i.Id === item.Id).length > 0) {
          listMap.push(item)
          selectIdMap.push(item.Id);
        }
      }
    });

    this.props.onChange({ list: listMap, selectId: selectIdMap });
  }
  SetDataFrom = (value) => {

    this.props.onChange({ dataFrom: parseInt(value), list: [], selectId: [] });
    if (parseInt(value) === 1) {

      this.GetProductList()
    }

  }
  deleteProduct = (Id) => {
    const { list } = this.props.value
    let data = list.filter(item => item.Id !== Id)
    this.props.onChange({ list: data });
  }
  SetTopNum = (num) => {
    this.setState({ selectTopnum: parseInt(num) }, () => {
      this.GetProductList();
      this.props.onChange({ topNum: parseInt(num) });
    })

  }
  SetSort = (e) => {
    this.setState({ selectSort: e }, () => {
      this.GetProductList();
      this.props.onChange({ sort: e });
    })

  }
  GetFirstAndSecondList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'goods/GetFirstAndSecondList',
      callBack: {
        success: res => {
          let arr = [],
            obj = {};
          if (res.Data != null) {
            res.Data.map(item => {
              obj = {};
              obj.title = item.Name;
              obj.value = '0-' + item.Id;
              obj.key = '0-' + item.Id;
              //obj.disabled = true;
              if (item.SecondList != null) {
                obj.children =
                  item.SecondList.length > 0 &&
                  item.SecondList.map(o => {
                    return {
                      title: o.Name,
                      value: '0-0-' + o.Id,
                      key: '0-0-' + o.Id,
                    };
                  });
              }
              arr.push(obj);
            });
            this.setState({
              treeData: arr,
            });
          }
        },
        error: res => {
          message.error(res.Msg);
        },
      },
    });
  };

  GetProductList = () => {
    const { dispatch } = this.props;
    const { selectSort, selectTopnum, selectValue, selectTap } = this.state
    if (!selectTopnum) {

      return;
    }
    let search = {
      PageIndex: 1,
      PageSize: selectTopnum,
      GroupIds: selectValue && selectValue.length > 0 ? selectValue.filter(item => item) : null,
      p: Math.random()
    }
    if (selectSort === 1) {
      search = { ...search, SortName: "CreateTime", Sort: "Desc" }
    } else if (selectSort === 2) {
      search = { ...search, SortName: "SaleNum", Sort: "Desc" }
    } else if (selectSort === 3) {
      search = { ...search, SortName: "SalePrice", Sort: "Desc" }
    } else if (selectSort === 4) {
      search = { ...search, SortName: "SalePrice", Sort: "Asc" }
    }
    dispatch({
      type: 'pruductSellList/GetSellProductList',
      payload: search,
      callBack: {
        success: res => {
          if (res.Code === 0) {

            this.props.onChange({ list: res.Data.DataList });
          }
        },
        error: res => {
          message.error(res.Msg);
        },
      },
    });
  }
  SetProductLayout = (e) => {
    this.props.onChange({ productLayout: parseInt(e.target.value) });
  }
  SetProductStyle = (e) => {
    this.props.onChange({ style: parseInt(e.target.value) });
  }
  SetShowOpts = (values) => {

    this.props.onChange({ showOpts: values });

  }
  SetCid = (values) => {

    let arr = [];
    let carr = [];
    values.map(item => {
      let id = item.split('0-0-')[1] || 0;
      if (id != 0) {
        carr.push(id);
        arr.push(item);
      }

    });
    this.setState({ selectValue: carr }, () => {
      this.GetProductList();
      this.props.onChange({ cid: values });
    })

  }

}

const ProductEdit = DragDropContext(HTML5Backend)(ProductEditor);
export default ProductEdit